package com.interceptor;

import com.common.dao.LoginMapper;
import com.common.dto.LoginDto;
import com.utils.result.Ret;
import com.utils.tools.JsonResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author: xufan
 * @Description 用户token校验拦截
 **/
@Component
public class AuthInterceptor implements HandlerInterceptor {
    private final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);
    @Resource
    private LoginMapper loginMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("request请求地址path[{}] uri[{}]", request.getServletPath(), request.getRequestURI());
        //request.getHeader(String) 从请求头中获取数据
        LoginDto loginDto = new LoginDto();
        String token = request.getHeader("token");
        if (StringUtils.isNotEmpty(token)) {
            loginDto.setToken(token);
            Map<String, Object> employeeMap = getEmployeeInfoByToken(loginDto);
            if (employeeMap != null) {
                request.setAttribute("employeeMap", employeeMap);
                return true;
            }
        }
        //登录超时，继续往接口层调用，返回固定格式内容
        JsonResponse.responseOutWithJson(response, Ret.failNoLogin("登陆已超时，请重新登录"));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    /**
     * @author: xufan
     * @Date: 2021/8/5
     * @Description: 根据token获取员工信息
     */
    private Map<String, Object> getEmployeeInfoByToken(LoginDto loginDto) {
        return loginMapper.getEmployeeInfoByToken(loginDto);
    }
}
